import { email, maxLength, minLength, required } from 'vuelidate/lib/validators';
import { Component, Inject, Vue } from 'vue-property-decorator';
import UserManagementService from './user-management.service';
import { IUser, User } from '@/shared/model/user.model';

const loginValidator = (value: string) => {
  if (!value) {
    return true;
  }
  return /<%- LOGIN_REGEX %>/.test(value);
};

const validations: any = {
  userAccount: {
    login: {
      required,
      maxLength: maxLength(254),
      pattern: loginValidator
    },
    firstName: {
      maxLength: maxLength(50)
    },
    lastName: {
      maxLength: maxLength(50)
    },
    email: {
      required,
      email,
      minLength: minLength(5),
      maxLength: maxLength(50)
    }
  }
};

@Component({
  validations
})
export default class <%=jhiPrefixCapitalized%>UserManagementEdit extends Vue {
  @Inject('userService') private userManagementService: () => UserManagementService;
  public userAccount: IUser;
  public isSaving = false;
  public authorities: any[] = [];
  public languages: any = this.$store.getters.languages;

  beforeRouteEnter(to, from, next) {
    next(vm => {
      vm.initAuthorities();
      if (to.params.userId) {
        vm.init(to.params.userId);
      }
    });
  }

  public constructor() {
    super();
    this.userAccount = new User();
    this.userAccount.authorities = [];
  }

  public initAuthorities() {
    this.userManagementService()
      .retrieveAuthorities()
      .then(_res => {
        this.authorities = _res.data;
      });
  }

  public init(userId: <% if (pkType === 'String' || pkType === 'UUID') { %>string<% } else { %>number<% } %>): void {
    this.userManagementService().get(userId).then(res => {
      this.userAccount = res.data;
    });
  }

  public previousState(): void {
    (<any> this).$router.go(-1);
  }

  public save(): void {
    this.isSaving = true;
    if (this.userAccount.id) {
      this.userManagementService().update(this.userAccount).then((res) => {
        this.returnToList();
        this.$root.$bvToast.toast(this.getMessageFromHeader(res).toString(), {
          toaster: 'b-toaster-top-center',
          title: 'Info',
          variant: 'info',
          solid: true,
          autoHideDelay: 5000,
        });
      });
    } else {
      <%_ if (!enableTranslation) { _%>
      this.userAccount.langKey = 'en';
      <%_ } _%>
      this.userManagementService().create(this.userAccount).then(res => {
        this.returnToList();
        this.$root.$bvToast.toast(this.getMessageFromHeader(res).toString(), {
          toaster: 'b-toaster-top-center',
          title: 'Success',
          variant: 'success',
          solid: true,
          autoHideDelay: 5000,
        });
      });
    }
  }

  private returnToList(): void {
    this.isSaving = false;
    (<any> this).$router.go(-1);
  }

  private getMessageFromHeader(res: any): any {
    <%_
    const headerAlert = `X-${frontendAppName}-alert`.toLowerCase();
    const headerParams = `X-${frontendAppName}-params`.toLowerCase();
    if (enableTranslation) {
    _%>
    return this.$t(res.headers['<%=headerAlert%>'], { param: decodeURIComponent(res.headers['<%=headerParams%>'].replace(/\+/g, ' ')) });
    <%_ } else {_%>
    return res.headers['<%=headerAlert%>'];
    <%_ } _%>
  }
}
